package com.projects.android.views;

import java.util.ArrayList;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.projects.android.R;
import com.projects.android.adapters.ManageOrdersAdapter;
import com.projects.android.bus.OrdersBUS;
import com.projects.android.dto.OrderDetailDTO;
import com.projects.android.dto.OrdersDTO;
import com.projects.android.utils.SelectedItems;
import com.projects.android.utils.Utils;

public class ManageOrders extends ListActivity {
	private TextView lblHeaderIDOrder;
	private TextView lblHeaderOrderDate;
	private TextView lblHeaderRestaurant;
	private ArrayList<OrdersDTO> orders;
	private Intent intent;
	public static ManageOrders Instance;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.manageorders);
		initTable();
		loadData();
		Instance = this;
	}

	public void initTable() {
		lblHeaderIDOrder = (TextView) findViewById(R.id.lblHeaderIDOrder);
		lblHeaderOrderDate = (TextView) findViewById(R.id.lblHeaderOrderDate);
		lblHeaderRestaurant = (TextView) findViewById(R.id.lblHeaderRestaurant);

		lblHeaderIDOrder.getLayoutParams().width = 20;
		lblHeaderRestaurant.getLayoutParams().width = Utils.SCREEN_WIDTH / 2 - 30;
		lblHeaderOrderDate.getLayoutParams().width = Utils.SCREEN_WIDTH / 2 + 10;
	}

	public void loadData() {
		orders = OrdersBUS
				.selectByIDUsers(SelectedItems.SelectedUsers.getID());
		if (orders != null) {
			ManageOrdersAdapter adapter = new ManageOrdersAdapter(this,
					R.layout.orderitem, R.id.lblIDOrder, orders);
			setListAdapter(adapter);
			getListView().setTextFilterEnabled(true);
		}
	}

	public void onListItemClick(ListView parent, View v, int pos, long id) {
		// TODO Auto-generated method stub
		if (pos >= 0 && pos < orders.size()) {
			final OrdersDTO order = orders.get(pos);

			final ProgressDialog dialog = new ProgressDialog(this);
			dialog.setTitle("Loading. Please wait...");
			dialog.setIndeterminate(true);

			final Thread thread = new Thread(new Runnable() {
				@Override
				public void run() {
					runOnUiThread(new Runnable() {
						ArrayList<OrderDetailDTO> data = order.getOrderDetails();

						@Override
						public void run() {
							SelectedItems.SelectedOrder = order;
							OrderDetails.Details = data;
							intent = Utils.browseIntent(ManageOrders.this,
									"OrderDetails");
							startActivity(intent);
							dialog.dismiss();
						}
					});
				}
			});
			dialog.show();
			thread.start();
		}
	}
}
